import React, { useState, useEffect } from 'react';
import { getVNCInfo } from '../api/client';

interface VNCInfo {
  host: string;
  port: number;
  websocket_port: number;
  password?: string;
  console_websocket_url?: string;
}

interface VNCViewerProps {
  domainName: string;
  isOpen: boolean;
  onClose: () => void;
}

const VNCViewerFixed: React.FC<VNCViewerProps> = ({ domainName, isOpen, onClose }) => {
  const [vncInfo, setVNCInfo] = useState<VNCInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    if (isOpen && domainName) {
      loadVNCInfo();
    }
  }, [isOpen, domainName]);

  const loadVNCInfo = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getVNCInfo(domainName);
      setVNCInfo(response.data);
      setConnected(true);
    } catch (err: any) {
      console.error('Failed to load VNC info:', err);
      setError(err.response?.data?.detail || 'Failed to load VNC information');
      setConnected(false);
    } finally {
      setLoading(false);
    }
  };

  const getVNCConnectionString = (info: VNCInfo) => {
    const host = info.host || 'localhost';
    const port = info.port || 5900;
    const wsPort = info.websocket_port || (port - 5900 + 6900);

    return {
      vncHost: host,
      vncPort: port,
      wsPort: wsPort,
      connectionString: `${host}:${port}`,
      wsConnectionString: `${host}:${wsPort}`
    };
  };

  const handleDirectVNCConnection = () => {
    if (vncInfo) {
      const conn = getVNCConnectionString(vncInfo);
      // 打开系统默认的VNC客户端
      const vncUrl = `vnc://${conn.connectionString}`;
      window.open(vncUrl, '_blank');
    }
  };

  const handleDownloadVNCFile = () => {
    if (vncInfo) {
      const conn = getVNCConnectionString(vncInfo);
      const vncContent = `[Connection]
Host=${conn.vncHost}
Port=${conn.vncPort}
Password=${vncInfo.password || ''}
`;

      const blob = new Blob([vncContent], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${domainName}.vnc`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  if (!isOpen) {
    return null;
  }

  return (
    <div className="vnc-viewer-modal">
      <div className="vnc-modal-overlay" onClick={onClose}>
        <div className="vnc-modal-content" onClick={(e) => e.stopPropagation()}>
          <div className="vnc-modal-header">
            <h2>VNC Connection - {domainName}</h2>
            <button className="vnc-close-btn" onClick={onClose} title="Close">
              ✕
            </button>
          </div>

          <div className="vnc-modal-body">
            {loading && (
              <div className="vnc-loading">
                <div className="loading-spinner"></div>
                <p>Loading VNC information...</p>
              </div>
            )}

            {error && (
              <div className="vnc-error">
                <div className="error-icon">⚠️</div>
                <h3>VNC Connection Error</h3>
                <p>{error}</p>
                <div className="error-actions">
                  <button onClick={loadVNCInfo} className="primary">
                    Retry
                  </button>
                  <button onClick={onClose} className="secondary">
                    Close
                  </button>
                </div>
              </div>
            )}

            {vncInfo && !loading && !error && (
              <div className="vnc-connection-info">
                <div className="vnc-info-panel">
                  <h4>VNC Connection Information</h4>
                  <div className="info-grid">
                    <div className="info-item">
                      <span className="info-label">Host:</span>
                      <span className="info-value">{vncInfo.host}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">VNC Port:</span>
                      <span className="info-value">{vncInfo.port}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">WebSocket Port:</span>
                      <span className="info-value">{vncInfo.websocket_port || (vncInfo.port - 5900 + 6900)}</span>
                    </div>
                    {vncInfo.password && (
                      <div className="info-item">
                        <span className="info-label">Password:</span>
                        <span className="info-value">••••••••</span>
                      </div>
                    )}
                  </div>
                </div>

                <div className="vnc-connection-options">
                  <h4>Connection Options</h4>

                  <div className="connection-methods">
                    <div className="method-card">
                      <h5>Direct VNC Client</h5>
                      <p>Use your system VNC client to connect directly</p>
                      <div className="connection-details">
                        <code>{getVNCConnectionString(vncInfo).connectionString}</code>
                      </div>
                      <button onClick={handleDirectVNCConnection} className="primary">
                        Open VNC Client
                      </button>
                      <button onClick={handleDownloadVNCFile} className="secondary">
                        Download .vnc File
                      </button>
                    </div>

                    <div className="method-card">
                      <h5>Web-based VNC</h5>
                      <p>Use a web-based VNC client (requires additional setup)</p>
                      <div className="connection-details">
                        <p><strong>WebSocket URL:</strong></p>
                        <code>ws://localhost:{getVNCConnectionString(vncInfo).wsPort}/websockify</code>
                      </div>
                      <button
                        className="secondary"
                        disabled
                        title="Web-based VNC requires additional server setup"
                      >
                        Launch Web VNC (Beta)
                      </button>
                      <p className="method-note">
                        Note: Web-based VNC requires a WebSocket-to-VNC proxy server
                      </p>
                    </div>
                  </div>

                  <div className="vnc-instructions">
                    <h5>Connection Instructions:</h5>
                    <ol>
                      <li>Choose your preferred connection method above</li>
                      <li>For Direct VNC: Make sure you have a VNC client installed</li>
                      <li>For Web VNC: Ensure the WebSocket proxy is running on port {getVNCConnectionString(vncInfo).wsPort}</li>
                      <li>Enter the password if required: {vncInfo.password ? 'Yes (hidden)' : 'No password'}</li>
                    </ol>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="vnc-modal-footer">
            <div className="connection-status">
              <span className={`status-indicator ${connected ? 'connected' : 'disconnected'}`}>
                {connected ? '🟢 Connected' : '🔴 Disconnected'}
              </span>
            </div>
            <button onClick={loadVNCInfo} className="secondary">
              Refresh Info
            </button>
            <button onClick={onClose} className="secondary">
              Close
            </button>
          </div>
        </div>
      </div>

      <style>{`
        .vnc-viewer-modal {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 1000;
        }

        .vnc-modal-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
        }

        .vnc-modal-content {
          background: white;
          border-radius: 8px;
          box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
          max-width: 95vw;
          max-height: 95vh;
          width: 800px;
          height: 600px;
          display: flex;
          flex-direction: column;
        }

        .vnc-modal-header {
          padding: 20px;
          border-bottom: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .vnc-modal-header h2 {
          margin: 0;
          font-size: 1.5em;
          color: #333;
        }

        .vnc-close-btn {
          background: none;
          border: none;
          font-size: 1.5em;
          cursor: pointer;
          padding: 5px;
          border-radius: 4px;
        }

        .vnc-close-btn:hover {
          background: #f0f0f0;
        }

        .vnc-modal-body {
          flex: 1;
          padding: 20px;
          overflow: auto;
        }

        .vnc-loading, .vnc-error {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          text-align: center;
        }

        .loading-spinner {
          width: 40px;
          height: 40px;
          border: 4px solid #f3f3f3;
          border-top: 4px solid #007bff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-bottom: 20px;
        }

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        .vnc-error .error-icon {
          font-size: 3em;
          margin-bottom: 20px;
        }

        .vnc-error h3 {
          margin: 0 0 10px 0;
          color: #dc3545;
        }

        .vnc-error p {
          margin: 0 0 20px 0;
          color: #666;
        }

        .error-actions {
          display: flex;
          gap: 10px;
        }

        .vnc-connection-info {
          display: flex;
          flex-direction: column;
          height: 100%;
          gap: 20px;
        }

        .vnc-info-panel {
          background: #f8f9fa;
          padding: 15px;
          border-radius: 6px;
          border: 1px solid #dee2e6;
        }

        .vnc-info-panel h4 {
          margin: 0 0 15px 0;
          color: #495057;
        }

        .info-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 10px;
        }

        .info-item {
          display: flex;
          justify-content: space-between;
          padding: 5px 0;
        }

        .info-label {
          font-weight: bold;
          color: #495057;
        }

        .info-value {
          color: #6c757d;
          font-family: monospace;
        }

        .vnc-connection-options {
          flex: 1;
        }

        .vnc-connection-options h4 {
          margin: 0 0 15px 0;
          color: #333;
        }

        .connection-methods {
          display: flex;
          flex-direction: column;
          gap: 20px;
          margin-bottom: 20px;
        }

        .method-card {
          background: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 6px;
          padding: 20px;
        }

        .method-card h5 {
          margin: 0 0 10px 0;
          color: #495057;
        }

        .method-card p {
          margin: 0 0 15px 0;
          color: #6c757d;
        }

        .connection-details {
          background: #e9ecef;
          padding: 10px;
          border-radius: 4px;
          margin: 10px 0;
          font-family: monospace;
          font-size: 0.9em;
        }

        .method-note {
          font-size: 0.8em;
          color: #6c757d;
          font-style: italic;
          margin-top: 10px;
        }

        .vnc-instructions {
          background: #fff3cd;
          border: 1px solid #ffeaa7;
          border-radius: 6px;
          padding: 15px;
        }

        .vnc-instructions h5 {
          margin: 0 0 10px 0;
          color: #856404;
        }

        .vnc-instructions ol {
          margin: 0;
          padding-left: 20px;
          color: #856404;
        }

        .vnc-instructions li {
          margin-bottom: 5px;
        }

        .vnc-modal-footer {
          padding: 15px 20px;
          border-top: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .connection-status {
          font-size: 0.9em;
        }

        .status-indicator {
          font-weight: bold;
        }

        .status-indicator.connected {
          color: #28a745;
        }

        .status-indicator.disconnected {
          color: #dc3545;
        }

        button {
          padding: 8px 16px;
          border: 1px solid #ddd;
          border-radius: 4px;
          background: white;
          cursor: pointer;
          font-size: 0.9em;
        }

        button:hover:not(:disabled) {
          background: #f8f9fa;
        }

        button:disabled {
          background: #e9ecef;
          color: #6c757d;
          cursor: not-allowed;
        }

        button.primary {
          background: #007bff;
          color: white;
          border-color: #007bff;
        }

        button.primary:hover:not(:disabled) {
          background: #0056b3;
        }

        button.secondary {
          background: #6c757d;
          color: white;
          border-color: #6c757d;
        }

        button.secondary:hover:not(:disabled) {
          background: #545b62;
        }

        .error-actions {
          display: flex;
          gap: 10px;
        }
      `}</style>
    </div>
  );
};

export default VNCViewerFixed;